﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IP代理
{
    /// <summary>
    /// 代理管理帮助类  核心代理来自网络
    /// </summary>
    public class IPProxy
    {
        [System.Runtime.InteropServices.DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lPBuffer, int lpdwBufferLength);
        private const int INTERNET_OPTION_REFRESH = 0x000025;
        private const int INTERNET_OPTION_SETTINGS_CHANGED = 0x000027;

        public static bool Proxy(string ip, int port)
        {
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            //设置代理可用 
            rk.SetValue("ProxyEnable", 1);
            //设置代理IP和端口 
            rk.SetValue("ProxyServer", string.Format("{0}:{1}", ip, port));
            rk.Close();
            //使它立即生效
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
            if (IsUseful("www.baidu.com"))
            {
                return true;
            }
            CancelProxy();
            return false;
        }
        public static void CancelProxy()
        {
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            rk.SetValue("ProxyEnable", 0);
        }
        public static bool IsUseful(string ipOrHost)
        {
            using (System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping())
            { 
                try
                { 
                    return System.Net.NetworkInformation.IPStatus.Success.Equals(pingSender.Send(ipOrHost, 6000).Status);
                }
                catch
                {
                    return false;
                }
            }

        }

        //获得代理的IP和端口
        public static string GetProxyProxyServer()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            string ProxyServer = rk.GetValue("ProxyServer").ToString();
            rk.Close();
            return ProxyServer;

        }

        //判断是否使用代理
        public static bool UsedProxy()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (rk.GetValue("ProxyEnable").ToString() == "1")
            {
                rk.Close();
                return true;
            }
            else
            {
                rk.Close();
                return false;
            }
        }
    }
}
